
#include "Common.h"
#include "HttpRequestHeader.h"

namespace fx {

    HttpRequestHeader::~HttpRequestHeader()
    {

    }

    HttpRequestHeader::HttpRequestHeader()
    {
    }

    HttpRequestHeaderPtr HttpRequestHeader::Create()
    {
        return HttpRequestHeaderPtr(new HttpRequestHeader());
    }
    HttpRequestHeaderPtr HttpRequestHeader::Create(const std::string& str_buf)
    {
        HttpRequestHeaderPtr header = HttpRequestHeader::Create();
        if (header->Parse(str_buf)) {
            return header;
        }
        return HttpRequestHeaderPtr();
    }
    HttpRequestHeaderPtr HttpRequestHeader::Create(std::istream& iss)
    {
        HttpRequestHeaderPtr header = HttpRequestHeader::Create();
        if (header->Parse(iss)) {
            return header;
        }
        return HttpRequestHeaderPtr();
    }

    bool HttpRequestHeader::ParseFirstLine()
    {
        std::vector<std::string> results;
        boost::algorithm::split(results, first_line_, boost::is_any_of(" "));
        if (results.size() != 3)
            return false;
        method_ = boost::algorithm::trim_copy(results[0]);
        path_ = boost::algorithm::trim_copy(results[1]);
        protocol_ = boost::algorithm::trim_copy(results[2]);
        // version
        boost::algorithm::split(results, protocol_, boost::is_any_of("/"));
        if (results.size() != 2)
            return false;
        protocol_ = boost::algorithm::trim_copy(results[0]);
        version_ = boost::algorithm::trim_copy(results[1]);
        return true;
    }
    void HttpRequestHeader::UpdateFirstLine()
    {
        first_line_ = (method_ + " " + path_ + " " + protocol_ + "/" + version_);
    }

    void HttpRequestHeader::SetMethod(const std::string& method)
    {
        if (method != method_) {
            method_ = method;
            UpdateFirstLine();
        }
    }
    void HttpRequestHeader::SetPath(const std::string& path)
    {
        if (path != path_) {
            path_ = path;
            UpdateFirstLine();
        }
    }
    void HttpRequestHeader::SetProtocol(const std::string& protocol)
    {
        if (protocol != protocol_) {
            protocol_ = protocol;
            UpdateFirstLine();
        }
    }
    void HttpRequestHeader::SetVersion(const std::string& version)
    {
        if (version != version_) {
            version_ = version;
            UpdateFirstLine();
        }
    }

}
